//
//  SWPhotoEditorEntranceViewController.swift
//  MiU
//  图片编辑器入口页面（图片选取、裁剪之后，再到编辑器页面PhotoEditorViewController）
//  Created by linhan on 16/1/4.
//  Copyright © 2016年 MiU. All rights reserved.
//

import Foundation
import UIKit
import AssetsLibrary


struct SWPhotoEditorOptions
{
    //发布完之后跳转到feed流页面
    var jumpToFeedFlow:Bool = true
    var topicEnable:Bool = true
    var topics:[String] = []
    var categoryName:String = ""
    var notifyWhenPublishSuccess:Bool = true
}

protocol PhotoEditorEntranceViewControllerDelegate:NSObjectProtocol
{
    func photoEditorEntranceViewControllerPublishSuccess(viewController:SWPhotoEditorEntranceViewController)
    
}

class SWPhotoEditorEntranceViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,PulldownContainerDelegate,SWImageCropperDelegate,PhotoEditorViewControllerDelegate,SWTakePhotoViewControllerDelegate,SWAssetsLibraryHelperDelegate
{
    var successCallback:((String)->Void)?
    var cancelCallback:(()->Void)?
    
    var categoryName:String = ""
    var options:SWPhotoEditorOptions = SWPhotoEditorOptions()
    
    private var _pulldownContainer:PulldownContainer = PulldownContainer()
    private var _library:ALAssetsLibrary = ALAssetsLibrary()
    
    private var _groups:[SWALAlbum] = []
    private var _photos:[SWALPhoto] = []
    private var _takePhotoItem:SWALPhoto = SWALPhoto(thumbnail:UIImage(named:"editor_icon_camera"))
    
    lazy private var _tableView:UITableView = UITableView()
    lazy private var _deniedTipLabel:UILabel = UILabel()
    lazy private var _noPhotoTipLabel:UILabel = UILabel()
    
    lazy private var _headerView:SWAlbumHeaderView = SWAlbumHeaderView()
    
    private var _collectionView:UICollectionView?
    
    deinit
    {
        trace("DEINIT SWPhotoEditorEntranceViewController")
    }
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        setup()
    }
    
    override func viewWillLayoutFirstTime() {
        
    }
    
    override func viewWillDisappear(animated: Bool)
    {
        super.viewWillDisappear(animated)
        if _pulldownContainer.state != .Closed
        {
            _pulldownContainer.close(false)
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        //SWAssetsLibraryHelper.shared().removeDelegate(self)
    }
    
    private func setup()
    {
        let tapGesture:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(headerViewTapped))
        _headerView.addGestureRecognizer(tapGesture)
        navigationItem.titleView = _headerView
        
        createNavigationLeftButton("X", target: self, action: #selector(closeBtnTapped))
        
        _tableView.frame = CGRectMake(0, 0, view.width, 0)
        _tableView.tableFooterView = UIView()
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor(hex: 0xeceeef)
        _tableView.rowHeight = SWThemeStyle.CameraRollCellHeight
        _tableView.separatorColor = SWAppearanceManager.themeStyle.tableViewSeparatorColor
        _tableView.separatorInset = UIEdgeInsetsZero
        if #available(iOS 8.0, *) {
            _tableView.layoutMargins = UIEdgeInsetsZero
        }
        
        _pulldownContainer.modelInsets = UIEdgeInsetsMake(navigationBarBottom, 0, 0, 0)
        _pulldownContainer.offset = CGPointMake(0, navigationBarBottom)
        _pulldownContainer.delegate = self
        
        var numOfHorizontal:Int = 4
        if SWDevice.size > .iPhone47inch{
            numOfHorizontal = 5
        }
        
        let Grid:CGFloat = 4
        let cellWidth:CGFloat = (self.view.width - (CGFloat(numOfHorizontal + 1) * Grid)) / CGFloat(numOfHorizontal)
        let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(cellWidth, cellWidth)
        //横向最小间隔
        layout.minimumInteritemSpacing = Grid
        //纵向最小间隔
        layout.minimumLineSpacing = Grid
        layout.sectionInset = UIEdgeInsetsMake(Grid, Grid, Grid, Grid)
        
        //_collectionView = UICollectionView(frame: CGRectMake(0, 0, view.width, view.height), collectionViewLayout: layout)
        _collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        _collectionView?.backgroundColor = UIColor.white
        _collectionView?.registerClass(SWAssetCollectionCell.self, forCellWithReuseIdentifier: "SWAssetCollectionCell")
        _collectionView?.dataSource = self
        _collectionView?.delegate = self
        _collectionView?.hidden = true
        view.addSubview(_collectionView!)
        _collectionView?.snp_makeConstraints(closure: {make in
            make.edges.equalTo(view)
        })
        
        let WarningTextFont:UIFont = SWAppearanceManager.themeStyle.fontOfSize(15)
        _deniedTipLabel = UILabel.labelWithLimitWidth(view.frame.width - 20, text: "请到 设置-》隐私-》照片中设置允许使用你的照片", font: WarningTextFont)
        _deniedTipLabel.hidden = true
        _deniedTipLabel.textColor = UIColor.darkGray
        _deniedTipLabel.textAlignment = .center
        view.addSubview(_deniedTipLabel)
        _deniedTipLabel.snp_makeConstraints(closure: {make in
            make.center.equalTo(view)
        })
        
        _noPhotoTipLabel = UILabel.labelWithLimitWidth(view.frame.width - 20, text: "相册中没有任何照片", font: WarningTextFont)
        _noPhotoTipLabel.hidden = true
        _noPhotoTipLabel.textColor = UIColor.darkGray
        _noPhotoTipLabel.textAlignment = .center
        view.addSubview(_noPhotoTipLabel)
        _noPhotoTipLabel.snp_makeConstraints(closure: {make in
            make.center.equalTo(view)
        })
        
        SWAssetsLibraryHelper.shared().addDelegate(self)
        SWAssetsLibraryHelper.shared().fetchAlbum()
    }
    
    //选择某个相册
    private func selectAlbum(album:SWALAlbum)
    {
        _headerView.name = album.name
        SWAssetsLibraryHelper.shared().fetchPhotoList(album: album)
    }
    
    private func processImage(image:UIImage, resize:Bool = true)
    {
        var result:UIImage = image
        if resize
        {
            result = Toucan.Resize.resizeImage(image, size: SW.Config.ProcessImagePresetSize, fitMode:.Crop)
        }
        
        //使用PW imageScaledToConstrainSize重压
        let size = CGSizeMake(CGFloat(CGImageGetWidth(result.CGImage)), CGFloat(CGImageGetHeight(result.CGImage)))
        result = result.imageScaledToConstrainSize(size).retinaImage ?? result
        
        let editor = SWPhotoEditorViewController(origin: result)
        editor.delegate = self
        navigationController?.pushViewController(editor, animated: true)
    }
    
    private func selectImage(image:UIImage)
    {
        let viewController:SWImageCropperViewController = SWImageCropperViewController(image: image)
        viewController.delegate = self
        presentViewController(viewController, animated: true, completion: nil)
    }
    
    private func presentTakePhotoViewController()
    {
        let viewController:SWTakePhotoViewController = SWTakePhotoViewController()
        viewController.delegate = self
        //viewController.albumImage = _groups.valueAt(0)?.thumbImage
        let nav:SWBaseNavigationController = SWBaseNavigationController(rootViewController: viewController)
        presentViewController(nav, animated: true, completion: nil)
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let Identifier:String = "SWAlbumCell"
        var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(Identifier) as? SWAlbumCell
        if cell == nil
        {
            cell = SWAlbumCell(style: UITableViewCellStyle.Default, reuseIdentifier: Identifier, cellWidth: view.width)
            cell?.accessoryType = .DisclosureIndicator
        }
        (cell as? SWAlbumCell)?.album = _groups.valueAt(indexPath.row)
        return cell ?? UITableViewCell()
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _groups.count
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if let album = _groups.valueAt(indexPath.row)
        {
            selectAlbum(album)
        }
        _pulldownContainer.close()
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return _photos.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
    {
        let cell:SWAssetCollectionCell = collectionView.dequeueReusableCellWithReuseIdentifier("SWAssetCollectionCell", forIndexPath: indexPath) as! SWAssetCollectionCell
        let index:Int = indexPath.row
        if let photo = _photos.valueAt(index)
        {
            cell.photo = photo
            photo.fetchThumbnail()
        }
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
    {
        let index:Int = indexPath.row
        if index == 0
        {
            presentTakePhotoViewController()
        }
        else
        {
            if let photo = _photos.valueAt(index)
            {
                var options = SWALPhotoRequestOptions()
                options.requestImageData = true
                SWAssetsLibraryHelper.shared().fetchOriginImage([photo], completeCallback: {results in
                    if let image = results.valueAt(0)?.image{
                        self.selectImage(image)
                    }
                    
                }, options:options)
            }//end photo
        }//end else
    }
    
    
    //授权被拒绝
    func requestAuthorizationDenied()
    {
        _deniedTipLabel.hidden = false
    }
    
    //相册获取完成
    func albumFetchComplete(album:[SWALAlbum], defaultAlbum:SWALAlbum?)
    {
        trace("albumFetchComplete", album.count, NSThread.currentThread())
        let count = album.count
        let TableViewHeight:CGFloat = min(self.view.height - 64, SWThemeStyle.CameraRollCellHeight * CGFloat(count))
        _groups = album
        _tableView.height = TableViewHeight
        _tableView.reloadData()
        _collectionView?.hidden = false
        _pulldownContainer.content = _tableView
        if let defaultAlbum = defaultAlbum
        {
            selectAlbum(defaultAlbum)
        }
    }
    
    //相册空
    func albumFetchEmpty()
    {
        _noPhotoTipLabel.hidden = false
    }
    
    //相片获取
    func photosFetchComplete(photos:[SWALPhoto])
    {
        trace("photosFetchComplete", NSThread.currentThread())
        _photos = []
        _photos.append(_takePhotoItem)
        _photos += photos
        _collectionView?.reloadData()
        _collectionView?.alpha = 0
        UIView.animateWithDuration(0.2, animations: {
            self._collectionView?.alpha = 1
        })
    }
    
    func willPresentPulldownContainer()
    {
        _headerView.open()
    }
    
    func willDismissPulldownContainer()
    {
        _headerView.close()
    }
    
    func takePhotoViewController(viewController:SWTakePhotoViewController, didFinishPickingImage image:UIImage)
    {
        processImage(image)
    }
    
    func photoEditorViewController(controller:SWPhotoEditorViewController, didFinishProcessImage processedImage:UIImage, additionInfo info:[NSObject:AnyObject]?)
    {
        let viewController:SWPhotoPublishViewController = SWPhotoPublishViewController(image:processedImage)
        viewController.successCallback = {[weak self] url in
            self?.successCallback?(url)
        }
        navigationController?.pushViewController(viewController, animated: true)
    }
    
    /**
    func publishViewControllerPublishSuccess(viewController:PicturePublishViewController, feed:MUGirlPost)
    {
        
    }**/
    
    func imageCropperViewController(viewController:SWImageCropperViewController, didFinishCroppingImage croppedImage:UIImage)
    {
        processImage(croppedImage, resize: false)
    }
    
    func imagePickerDidFinishPickingImage(image:UIImage?)
    {
        guard let image = image else{
            return
        }
        processImage(image)
    }
    
    @objc private func headerViewTapped()
    {
        if _pulldownContainer.state == .Closing || _pulldownContainer.state == .Opening
        {
            return
        }
        
        if _pulldownContainer.state == .Closed
        {
            _pulldownContainer.open()
        }
        else
        {
            _pulldownContainer.close()
        }
    }
    
    @objc private func closeBtnTapped()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}
